<template>
  <a-row :wrap="false" class="ant-row">
    <a-col flex="none" :style="{ width: '250px' }">
      <div class="title-bar">
        <img class="logo" src="../assets/logo.png" alt="logo" />
        <div class="title">智能食堂论坛</div>
      </div>
    </a-col>
    <a-col flex="auto" class="globalHeader-container">
      <div class="globalHeader">
        <!--        <a-input-search-->
        <!--          class="search-input"-->
        <!--          v-model:value="value"-->
        <!--          placeholder="搜索"-->
        <!--          @search="handleSearch"-->
        <!--        />-->
        <a-menu
          v-if="!isMobile"
          :key="menuKey"
          v-model:selected-keys="current"
          mode="horizontal"
          :items="items"
          class="custom-menu"
          @click="doMenuClick"
        />
        <div v-if="loginUserStore.loading" class="skeleton">
          <a-skeleton-circle :size="48" />
        </div>
        <template v-if="loginUserStore.loginUser?.id">
          <a href="/userSetting/setting">
            <a-avatar class="avatar" size="large" :src="avatarUrl">
              <template #icon><UserOutlined /></template>
            </a-avatar>
          </a>
        </template>
        <template v-else>
          <a-button
            type="primary"
            class="login-button"
            @click="openAuthModal('login')"
            >登录/注册</a-button
          >
        </template>
      </div>
    </a-col>
    <a-col flex="none" :style="{ width: '250px' }">
      <!--      <div class="right-side-menu">-->
      <!--        <a-dropdown :trigger="['click']">-->
      <!--          <a class="ant-dropdown-link" @click.prevent="handleSettingClick"-->
      <!--            ><SettingFilled class="setting-filled" />-->
      <!--          </a>-->

      <!--          <template #overlay>-->
      <!--            <a-menu v-if="loginUserStore.loginUser?.id">-->
      <!--              <a-menu-item>-->
      <!--                <a href="/userSetting/setting">账号设置</a>-->
      <!--              </a-menu-item>-->
      <!--              <a-menu-item>-->
      <!--                <a @click.prevent="handleLogout">退出登录</a>-->
      <!--              </a-menu-item>-->
      <!--            </a-menu>-->
      <!--          </template>-->
      <!--        </a-dropdown>-->
      <!--        <EditFilled class="edit-filled" @click="handleEditClick" />-->
      <!--      </div>-->
    </a-col>
  </a-row>
  <!--  <a-modal v-model:open="authStore.showCreateModal" :footer="null">-->
  <!--    <p-->
  <!--      style="-->
  <!--        text-align: left;-->
  <!--        font-weight: bold;-->
  <!--        font-size: 20px;-->
  <!--        color: #333333;-->
  <!--      "-->
  <!--    >-->
  <!--      快捷发布-->
  <!--    </p>-->
  <!--    <a-divider />-->
  <!--    <BlogCreate @blog-created="handleBlogCreated" />-->
  <!--  </a-modal>-->
  <a-modal v-model:open="authStore.showLoginModal" :footer="null">
    <div class="auth-container">
      <div class="tabs">
        <span
          @click="formType = 'login'"
          :class="{ active: formType === 'login' }"
          >登录</span
        >
        <span
          @click="formType = 'register'"
          :class="{ active: formType === 'register' }"
          >注册</span
        >
      </div>
    </div>
    <a-divider />
    <component :is="currentFormComponent" />
  </a-modal>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, watch } from "vue";
import { message } from "ant-design-vue";
import { h, ref } from "vue";
import {
  HomeOutlined,
  FireOutlined,
  UserOutlined,
  EditFilled,
  SettingFilled,
} from "@ant-design/icons-vue";
import { MenuProps } from "ant-design-vue";
import LoginView from "@/views/user/LoginView.vue";
import RegisterView from "@/views/user/RegisterView.vue";
import { useAuthStore, useUserStore } from "@/store/useLoginUserStore";
import { useLoginUserStore } from "@/store/useLoginUserStore";
import { logout } from "@/api/user";
import { useRouter } from "vue-router";
import { getMinioUrl } from "@/utils/minio";
import BlogCreate from "@/components/BlogCreate.vue";

const value = ref<string>("");
const userStore = useUserStore();
const loginUserStore = useLoginUserStore();

// 控制模态框显示
const showLoginModal = ref(false);
const formType = ref<"login" | "register">("login");
const currentFormComponent = computed(() => {
  return formType.value === "login" ? LoginView : RegisterView;
});
const router = useRouter();
const doMenuClick = ({ key }: { key: string }) => {
  if (key === "/hot") {
    router.push({ path: "/hot" });
    return;
  }
  if (!loginUserStore.loginUser?.id) {
    openAuthModal("login");
    return;
  }
  if (key === "/user") {
    const userId = loginUserStore.loginUser?.id;
    router.push({ path: `/user/${userId}` });
    return;
  }
  if (key.startsWith("/user/")) {
    const targetUserId = key.split("/")[2];
    if (targetUserId === String(loginUserStore.loginUser?.id)) {
      current.value = ["/user"]; // 当前用户，高亮
    } else {
      current.value = []; // 非当前用户，不高亮
    }
  }
  router.afterEach((to) => {
    if (to.path.startsWith("/user/")) {
      const targetUserId = to.params.userId as string;
      if (targetUserId === String(loginUserStore.loginUser?.id)) {
        current.value = ["/user"]; // 当前用户，高亮
      } else {
        current.value = []; // 非当前用户，不高亮
      }
    } else {
      current.value = [to.path]; // 默认路径处理
    }
  });
  router.push({ path: key });
};
const current = ref<string[]>(["mail"]);
const items = ref<MenuProps["items"]>([
  {
    key: "/comment/1",
    icon: () => h(HomeOutlined, { class: "menu-icon" }),
    title: "首页",
  },
  // {
  //   key: "/hot",
  //   icon: () => h(FireOutlined, { class: "menu-icon" }),
  //   title: "推荐",
  // },
  // {
  //   key: "/user",
  //   icon: () => h(UserOutlined, { class: "menu-icon" }),
  //   title: "用户",
  // },
]);
const isSmallScreen = ref(false);
const isMobile = ref(false);
const menuKey = ref(0);
const handleLogout = async () => {
  localStorage.removeItem("token");
  await logout();
  loginUserStore.$reset();
  setTimeout(() => {
    window.location.href = "/hot";
  }, 100);
};

function openAuthModal(type: "login" | "register") {
  formType.value = type;
  authStore.showLoginModal = true;
}

const authStore = useAuthStore();
watch(
  () => authStore.showLoginModal,
  (newVal) => {
    showLoginModal.value = newVal;
  }
);

function checkScreenWidth() {
  const width = window.innerWidth;
  isSmallScreen.value = width < 930;
  // isMobile.value = width < 930;
}

onMounted(async () => {
  checkScreenWidth();
  await loginUserStore.fetchLoginUser();
  const currentPath = router.currentRoute.value.path;
  const matchedItem = items.value?.find((item) =>
    currentPath.startsWith(item.key as string)
  );
  if (matchedItem) {
    current.value = [matchedItem.key as string];
  }
  window.addEventListener("resize", checkScreenWidth);
});

onUnmounted(() => {
  window.removeEventListener("resize", checkScreenWidth);
});

const avatarUrl = computed(() => {
  const avatar = loginUserStore.loginUser?.avatar;
  return userStore.avatarUrl || (avatar ? getMinioUrl(avatar) : "");
});

const handleSearch = (inputValue: string) => {
  const searchValue = inputValue?.trim(); // 去除空格
  if (!searchValue) {
    message.warning("请输入搜索内容");
    return;
  }

  if (!loginUserStore.loginUser?.id) {
    openAuthModal("login");
    return;
  }
  onSearch(searchValue);
};

const performSearch = (query: string) => {
  router.push({ path: "/search/blog", query: { q: query } });
};

const onSearch = async (searchValue: string) => {
  if (!searchValue.trim()) {
    message.warning("请输入搜索内容");
    return;
  }
  performSearch(searchValue);
  value.value = "";
};

const handleSettingClick = (e: Event) => {
  if (!loginUserStore.loginUser?.id) {
    openAuthModal("login");
    e.preventDefault();
    e.stopPropagation();
    return;
  }
};

const handleEditClick = () => {
  if (!loginUserStore.loginUser?.id) {
    openAuthModal("login");
    return;
  }
  authStore.showCreateModal = true;
};

const handleBlogCreated = async () => {
  window.location.reload();
};

watch(
  () => loginUserStore.loginUser,
  (newUser) => {
    if (newUser && router.currentRoute.value.path.startsWith("/user/")) {
      const userId = router.currentRoute.value.params.userId as string;
      if (userId === String(newUser.id)) {
        current.value = ["/user"];
      } else {
        current.value = [];
      }
    }
  },
  { immediate: true, deep: true }
);
</script>

<style scoped>
.title-bar {
  display: flex;
  justify-content: flex-end;
  margin-left: 0;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
}

.logo {
  height: 32px;
  margin: 15px;
}

.globalHeader-container {
  min-width: 800px;
}

.globalHeader {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 100vw; /* 新增 */
}
@media (max-width: 1150px) {
  .login-button {
    display: none;
  }
}

@media (max-width: 1370px) {
  .search-input,
  .setting-filled,
  .edit-filled {
    display: none; /* 更小屏下隐藏登录按钮 */
  }
}

/* 全屏或大屏下恢复显示 */
@media (min-width: 1370px) {
  .search-input,
  .login-button,
  .setting-filled,
  .edit-filled {
    display: inline-block !important;
  }
}

@media (max-width: 960px) {
  .title {
    display: none;
  }
}

@media (min-width: 960px) {
  .title {
    display: inline-block !important;
  }
}

:deep(.ant-menu-item) {
  height: 65px !important;
  line-height: 50px !important;
}

:deep(.ant-menu-item .ant-menu-item-icon) {
  display: flex;
  height: 100%;
  align-items: center;
  justify-content: center;
  width: 100px;
}

:deep(.menu-icon) {
  font-size: 25px !important;
}

.search-input {
  position: absolute;
  width: 200px;
  left: 20px;
}

.login-button {
  position: absolute;
  right: 50px;
}

.right-side-menu {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 20px;
  height: 100%;
  padding-right: 100px;
}

.edit-filled {
  color: rgb(22, 119, 255);
  font-size: 24px;
  cursor: pointer;
}

.setting-filled {
  color: rgb(22, 119, 255);
  font-size: 24px;
  cursor: pointer;
  margin-right: 15px;
}

.auth-container .tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.auth-container .tabs span {
  cursor: pointer;
  padding: 8px 16px;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
  font-size: 16px;
}

.auth-container .tabs span.active {
  border-color: #1890ff;
  color: #1890ff;
  font-weight: bold;
}

.avatar {
  position: absolute;
  right: 275px;
  cursor: pointer;
  top: 13px;
}

@media (max-width: 1500px) {
  .avatar {
    right: 10px;
  }
}

@media (max-width: 970px) {
  .avatar {
    display: none;
  }
}
</style>
